package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime,LocalDate.parse(start,DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }

    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     */
    @Override
    @Transactional
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        checkCreateTask(taskViewModel.getInnerCode(),taskViewModel.getProductType());//验证售货机框架
        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());
        BeanUtils.copyProperties(taskViewModel,taskEntity);
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        taskEntity.setAddr(vmInfo.getNodeAddr());
        taskEntity.setRegionId(vmInfo.getRegionId());
        this.save(taskEntity);
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d-> {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(d,detailsEntity);
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
        return true;
    }

    /**
     * 接受工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id);
        if(task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE){
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        return this.updateById(task);
    }

    /**
     * 取消工单
     *
     * @param id
     * @param cancelVM
     * @return
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);
        if(task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL){
            throw new LogicException("工单已经取消");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelVM.getDesc());
        return updateById(task);
    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(long id) {
        TaskEntity task = this.getById(id);
        if(task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL){
            throw new LogicException("工单已经取消");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        this.updateById(task);
        //如果是投放工单或撤机工单
        if(task.getTaskStatus() == VMSystem.TASK_TYPE_DEPLOY || task.getTaskStatus() == VMSystem.TASK_TYPE_REVOKE){
            noticeVMServiceStatus(task);
        }
        //如果是补货清单
        if(task.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            noticeVMServiceSupply(task);
        }
        return true;
    }

    private String generateTaskCode() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "lkd.task.code" + date;
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj == null){
            redisTemplate.opsForValue().set(key,1l, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(
                redisTemplate.opsForValue().increment(key,1).toString(),4,'0'
        );
    }

    /**
     * 创建工单校验
     * @param innerCode 设备编号
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(String innerCode,int productType) throws LogicException {
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        if(vmInfo == null) throw new LogicException("设备校验失败");
        //如果是投放工单，状态为运营
        if(productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getStatus() == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("设备已在运营状态");
        }
        //如果是补货工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getStatus() == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("设备不在运营状态");
        }
        //如果是撤机工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_REPAIR && vmInfo.getStatus() == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("设备不在运营状态");
        }
    }

    /**
     * 同一台设备下是否存在未完成的工单
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode,int productionType){
        QueryWrapper<TaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode,innerCode)
                .eq(TaskEntity::getProductTypeId,productionType)
                .le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        return count(queryWrapper) > 0;
    }

    /**
     * 运维工单封装与下发
     * @param taskEntity
     */
    private void noticeVMServiceStatus(TaskEntity taskEntity){
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,taskCompleteContract);
        } catch (JsonProcessingException e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }

    /**
     * 补货协议封装与下发
     * @param taskEntity
     */
    private void noticeVMServiceSupply(TaskEntity taskEntity){
        //协议内容封装
        //1.根据工单id查询工单明细表
        QueryWrapper<TaskDetailsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TaskDetailsEntity::getTaskId,taskEntity.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(queryWrapper);
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(taskEntity.getInnerCode());
        ArrayList<SupplyChannel> supplyChannels = Lists.newArrayList();
        details.forEach(d->{
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelId(d.getChannelCode());
            supplyChannel.setCapacity(d.getExpectCapacity());
            supplyChannels.add(supplyChannel);
        });
        supplyContract.setSupplyData(supplyChannels);
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,supplyContract);
        } catch (JsonProcessingException e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }
}
